package com.polaris.live.dialog

import android.content.Context
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import com.blankj.utilcode.util.StringUtils
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BottomPopupView
import com.polaris.live.R
import com.polaris.live.adapter.RoomSkinAdapter
import com.polaris.live.common.constant.AppConst
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.mvvm.viewmodel.BaseViewModel
import com.polaris.live.common.network.request
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.databinding.DialogRoomSkinBinding
import com.polaris.live.net.userService
import com.polaris.live.resp.back_resp.UserRoomThemeVo
import com.polaris.live.resp.go_resp.UserRoomThemeUseRequest
import com.polaris.live.translation.R.string
import com.polaris.live.utils.CommonUtils.toBoolean

/**
 * 房间皮肤
 *
 * @author Created by 半仙 on 2024/12/23/023 15:43
 */
class RoomSkinDialog(
    context: Context,
    private val mViewModel: BaseViewModel,
) : BottomPopupView(context) {

    override fun getImplLayoutId() = R.layout.dialog_room_skin

    private lateinit var mBinding: DialogRoomSkinBinding

    private val mAdapter by lazy { RoomSkinAdapter() }

    override fun onCreate() {
        super.onCreate()
        mBinding = DialogRoomSkinBinding.bind(popupImplView)

        mBinding.skinRecycler.apply {
            adapter = mAdapter
            itemAnimator = null
            layoutManager = GridLayoutManager(context, 3, GridLayoutManager.VERTICAL, false)
        }

        initListener()
        initObserver()
    }

    private fun initObserver() {
        mViewModel.request({ userService.getRoomTheme() }, {
            mBinding.widgetLoading.visibility = View.GONE
            mBinding.widgetEmpty.visibility = View.GONE
            val indexOf = it.list.indexOfFirst { it.useStatus.toBoolean() }

            val newList = it.list.toMutableList()
            newList.add(
                0, UserRoomThemeVo(
                    activated = true,
                    expireTime = null,
                    name = DEFAULT_NAME,
                    url = "",
                    useStatus = if (indexOf == -1) AppConst.YES else AppConst.NO
                )
            )
            mAdapter.setList(newList)
        }, {
            mBinding.widgetLoading.visibility = View.GONE
            mBinding.widgetEmpty.visibility = View.VISIBLE
        })
    }

    private fun initListener() {
        mBinding.closeImg.setOnSingleClickListener {
            dismiss()
        }

        mBinding.ivWhat.setOnSingleClickListener {
            RoomSkinDetailDialog.show(context)
        }

        mAdapter.setOnItemClickListener { _, _, position ->
            val item = mAdapter.getItemOrNull(position) ?: return@setOnItemClickListener

            //如果position是0那么 代表选中了默认，只需要把当前使用中的卸下来就好
            //如果不是走下面的逻辑
            if (position == 0) {
                selectDefault(item, position)
                return@setOnItemClickListener
            }

            if (!item.activated) {
                OpenVipDialog.show(
                    context,
                    StringUtils.getString(string.vip_four_level_open_background, "VIP${item.name}")
                )
                return@setOnItemClickListener
            }

            //如果点击的不是默认则切换
            if (item.useStatus.toBoolean()) return@setOnItemClickListener
            mViewModel.request({
                userService.useRoomTheme(UserRoomThemeUseRequest(item.name, AppConst.YES))
            }, {
                //把当前使用的状态修改
                val indexOf = mAdapter.data.indexOfFirst { it.useStatus.toBoolean() }
                if (indexOf != -1) {
                    mAdapter.getItemOrNull(indexOf)?.useStatus = AppConst.NO
                    mAdapter.notifyItemChanged(indexOf)
                }

                //替换新的状态
                item.useStatus = AppConst.YES
                mAdapter.notifyItemChanged(position)
                ToastGravity.showGravity(StringUtils.getString(string.skin_change_success))
            }, {
                ToastGravity.showGravity(it.errorMsg)
            })
        }
    }

    //切换到默认
    private fun selectDefault(item: UserRoomThemeVo, position: Int) {
        val indexOf = mAdapter.data.indexOfFirst { it.useStatus.toBoolean() }
        if (indexOf != -1) {
            val useItem = mAdapter.getItemOrNull(indexOf) ?: return
            mViewModel.request({
                userService.useRoomTheme(UserRoomThemeUseRequest(useItem.name, AppConst.NO))
            }, {
                useItem.useStatus = AppConst.NO
                mAdapter.notifyItemChanged(indexOf)

                item.useStatus = AppConst.YES
                mAdapter.notifyItemChanged(position)
            }, {
                ToastGravity.showGravity(it.errorMsg)
            })
        }
    }

    companion object {

        const val DEFAULT_NAME = ""            //默认名称给空就行

        fun show(context: Context, mViewModel: BaseViewModel) {
            XPopup.Builder(context)
                .isDestroyOnDismiss(true)
                .asCustom(RoomSkinDialog(context, mViewModel))
                .show()
        }
    }

}